const {loginModel, registerModel} = require('../models/user')
const jwt = require("jsonwebtoken");
//导入bcryptjs(密码加密)
const bcrypt = require("bcryptjs")

const loginHandler = async (req,res) => {
    const userLoginInfo = req.body
    let rs = await loginModel(userLoginInfo)
    if (rs){
        if (rs instanceof Error){
            res.send({
                meta:{
                    state:400,
                    msg:rs.message
                }
            })
        }else if (bcrypt.compareSync(userLoginInfo.password, rs.password)){
            const secretKey = 'loveSick'
            const tokenStr = jwt.sign({username:userLoginInfo.username},secretKey,{expiresIn:'24h'})
            res.send({
                meta:{
                    state:200,
                    msg:'登陆成功',
                    token:"Bearer " + tokenStr
                }
            })
        }else {
            res.send({
                meta:{
                    state:401,
                    msg:'登陆失败,用户名或密码输入错误'
                }
            })
        }
    }else {
        res.send({
            meta:{
                state:500,
                msg:'登陆失败'
            },
            data:null
        })
    }
}

const registerHandler = async (req,res) => {
    let userInfo = req.body
    let rs = await registerModel(userInfo)
    //判断返回
    if(rs){
        if (rs instanceof Error){
            res.send({
                meta:{
                    state:401,
                    msg:rs.message
                }
            })
        }else {
            res.send({
                meta:{
                    state:200,
                    msg:'添加成功'
                }
            })
        }
    }else {
        res.send({
            meta:{
                state:500,
                msg:'添加失败Api'
            }
        })
    }
}

module.exports = {
    loginHandler,
    registerHandler
}
